import socket
import os
import json

class ClientFtp(object):
    client = socket.socket()

    def __init__(self):
        self.client.connect(('localhost', 9999))

    def get(self, data):
        #发送信息给服务器端
        send_data = {
            'action': 'get_ack',
            'filename': data['filename']
        }
        self.client.send(json.dumps(send_data).encode())

        #接受反馈信息
        response = self.client.recv(1024)
        print(response)
        res = json.loads(response.decode())
        if res['flag'] == 'not':
            print('没有此文件')
        elif res['flag'] == 'ok':
            save_file = input('输入文件保存的位置：')

            # 给客户端发送确认信息
            send_ack = {
                'action': 'get_file',
                'filename': data['filename']
            }
            self.client.send(json.dumps(send_ack).encode())

            recv_size = 0
            filesize = res['filesize']
            f = open(save_file+os.sep+data['filename'], 'wb')
            while recv_size < filesize:
                recv_data = self.client.recv(1024)
                f.write(recv_data)
                recv_size += len(recv_data)


    def put(self, data):
        file = data['filename']
        filename = file.split(os.sep)[-1]
        if os.path.isfile(file):
            filesize = os.stat(file).st_size
            send_data = {
                'action': 'put_ack',
                'filename': filename,
                'filesize': filesize
            }

            # 发送文件信息给服务端
            self.client.send(json.dumps(send_data).encode())

            # 收到服务的确认
            response = self.client.recv(1024)
            res = response.decode()

            if res == 'ok':
                # 发送数据
                send_data_1 = {
                    'action': 'put_file',
                    'filename': filename,
                }
                f = open(file, 'r')
                for line in f:
                    send_data_1['content']=line
                    self.client.send(json.dumps(send_data_1).encode())
                    self.client.recv(1024)

                # send_data_1['flag'] = 'over'
                # self.client.send(json.dumps(send_data_1).encode())

            elif res == 'not':
                print('该文件已经存在了')

        else:
            print('the file does not exist...')


ftp_client = ClientFtp()

while True:
    deal_data = {}
    input_data = input(">> ").strip()

    if len(input_data) == 0:
        continue

    analysis_data = input_data.split()
    if len(analysis_data) != 2:
        print('cmd filename')
        continue
    else:
        deal_data['cmd'] = analysis_data[0]
        deal_data['filename'] = analysis_data[1]

    if hasattr(ftp_client, deal_data['cmd']):
        filename = input_data.split()[1]
        func = getattr(ftp_client, deal_data['cmd'])
        func(deal_data)
    else:
        print('没有此方法')